<template>
	<van-nav-bar title="添加子账号" left-text="返回" left-arrow @click-left="onClickLeft" />
	<div>
		<van-form @failed="onFailed" @submit="onSubmit" :validate-trigger="['onChange', 'onSubmit']" input-align="right"
			error-message-align="right">
			<van-cell-group inset title="填写账号信息">
				<!-- 账号 -->
				<van-field name="account" :rules="phoneRules" label="账号" v-model="form.account" placeholder="请输入手机号"
					required>
				</van-field>
				<!-- 名称 -->
				<van-field name="name" label="名称" v-model="form.name" placeholder="请输入名称" required
					:rules="[{ required: true, message: '请输入名称' }]">
				</van-field>
				<!-- 密码 -->
				<van-field v-model="form.password" type="password" placeholder="请输入密码" :rules="passwordRules" label="密码"
					required />

				<van-field v-model="form.confirmPassword" type="password" placeholder="请确认登录密码" required label="确认密码"
					:rules="confirmPasswordRules" />

			</van-cell-group>

			<van-cell-group inset title="设置账号权限">

				<van-field name="account" :rules="[{ required: true, message: '请选择账号权限' }]" label="账号权限"
					v-model="permission" placeholder="请选择账号权限" is-link readonly required @click="popupshow = true">
				</van-field>
			</van-cell-group>
			<div style="margin: 16px;">
				<van-button round block type="primary" native-type="submit">
					添加
				</van-button>
			</div>
		</van-form>
	</div>
	<!-- 设置权限 -->
	<van-popup v-model:show="popupshow" safe-area-inset-bottom position="bottom" @close="popclose">
		<div class="popupContent">
			<!-- <ul class="flexbetween">
				<li class="cancelClass">
					<p @click="popCancel">取消</p>
				</li>
				<li class="confirmClass">
					<p @click="popCon">确定</p>
				</li>
			</ul> -->
			<van-cell-group inset>
				<van-cell title="全选">
					<template #right-icon>
						<van-checkbox v-model="isCheckAll" :indeterminate="isIndeterminate" @change="checkAllChange">
						</van-checkbox>
					</template>
				</van-cell>
			</van-cell-group>

			<!-- 多选 -->
			<van-checkbox-group v-model="checkedResult" @change="checkedResultChange">
				<van-cell-group inset>
					<van-cell v-for="(item, index) in storelist" :key="index" :title="item.storeName"
						@click="toggle(index)">
						<template #right-icon>
							<van-checkbox :name="item.id" :ref="el => checkboxRefs[index] = el" @click.stop />
						</template>
					</van-cell>
				</van-cell-group>
			</van-checkbox-group>
		</div>
	</van-popup>

</template>

<script setup>
	import {
		ref,
		onMounted,
		onBeforeUpdate
	} from "vue";
	import {
		getUserid,
		getIdentity
	} from '@/utils/auth';
	import {
		deviceUsersAdd
	} from '@/api/deviceUsers';
	import {
		StoresList
	} from '@/api/deviceRechargeConfig';
	import {
		showToast
	} from 'vant';

	const checkboxRefs = ref([]);

	const toggle = (index) => {
		checkboxRefs.value[index].toggle();
		//console.log(checkedResult.value)
	};

	onBeforeUpdate(() => {
		checkboxRefs.value = [];
	});

	//全选
	const isCheckAll = ref(false);
	const isIndeterminate = ref(true);
	const checkedResult = ref([]);
	const maxCount = ref(0);

	const checkAllChange = (val) => {
		checkedResult.value = val ? storeid.value : []
		isIndeterminate.value = false
	}

	const checkedResultChange = (value) => {
		const checkedCount = value.length;
		maxCount.value = checkedCount;
		isCheckAll.value = checkedCount === storelist.value.length;
		isIndeterminate.value = checkedCount > 0 && checkedCount < storelist.value.length;
	};

	//取消
	const popCancel = () => {
		maxCount.value = 0;
		isCheckAll.value = false;
		isIndeterminate.value = true;
		checkedResult.value = [];
		permission.value = '';
		form.value.storeIds = [];
		popupshow.value = false;
	};

	const popclose = () => {
		if (maxCount.value > 0) {
			permission.value = '已设置';
		} else {
			permission.value = '';
		}
		form.value.storeIds = checkedResult.value;
	};

	// 确认
	const popCon = () => {
		if (maxCount.value > 0) {
			permission.value = '已设置';
		} else {
			permission.value = '';
		}
		form.value.storeIds = checkedResult.value;
		popupshow.value = false;
	};

	const storelist = ref([]); //商家列表
	const storeid = ref([]); //商家列表

	onMounted(() => {
		getcheckList(); //获取商家列表
	});

	const getcheckList = async () => {
		try {
			const userId = {
				userId: getUserid()
			};
			const response = await StoresList(userId);
			storelist.value = response.data || [];
			storeid.value = storelist.value?.map(item => item.id) || [];
		} catch (err) {
			//console.error('获取数据失败', err);
		}
	};


	// 手机号验证规则
	const phoneRules = [{
		required: true,
		message: '请输入手机号'
	}, {
		pattern: /^1[3-9]\d{9}$/,
		message: '手机号格式不正确'
	}];

	// 密码验证规则
	const passwordRules = [{
		required: true,
		message: '请输入密码'
	}, {
		pattern: /^.{6,8}$/,
		message: '密码需6-8位'
	}];

	const confirmPasswordRules = [{
		required: true,
		message: '请再次输入密码确认'
	}, {
		validator: (value) => value === form.value.password,
		message: '两次输入的密码不一致'
	}];
	// 权限
	const permission = ref('');
	const popupshow = ref(false);

	const form = ref({
		account: '',
		userId: getUserid(),
		name: '',
		password: '',
		confirmPassword: '',
		storeIds: []
	})

	const onSubmit = async (values) => {
		const Identity = getIdentity();
		if (Identity == 0) {
			showToast('请先完成商户审核再添加子账户');
		} else if (Identity == 1) {
			try {
				const response = await deviceUsersAdd(form.value);
				if (response.status == 200) {
					showToast({
						type: 'success',
						message: '添加成功',
						forbidClick: true,
						duration: 1000
					});
					setTimeout(() => {
						window.history.back();
					}, 1000)
				} else {
					showToast({
						type: 'fail',
						message: response.desc || '添加失败',
						forbidClick: true,
						duration: 1000
					});
				}
			} catch (err) {
				showToast({
					type: 'fail',
					message: err.desc || '添加失败',
					forbidClick: true,
					duration: 1000
				});
			}
		} else {
			showToast('二级账号无添加子账户权限');
		}
	};

	const onFailed = (errorInfo) => {
		//console.log('failed', errorInfo);
	};
	// 返回
	const onClickLeft = () => history.back();
</script>

<style lang="scss">
	:root:root {
		--van-cell-group-inset-padding: 0;
	}

	.popupContent {
		.van-cell {
			padding: 10px 0;
		}
	}
</style>

<style lang="scss" scoped>
	.title {
		background-color: rgb(245, 245, 245);
	}

	// ::-webkit-scrollbar {
	// 	display: none;
	// }
	.flexbetween {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.popupContent {
		max-height: 60vh;
		padding: 15px;
		box-sizing: border-box;

		.cancelClass {
			color: var(--van-text-color-2);

			p {
				margin-top: 0;
				cursor: pointer;
			}
		}

		.confirmClass {
			color: var(--van-primary-color);

			p {
				margin-top: 0;
				cursor: pointer;
			}
		}
	}
</style>